<?php

/**
* @desc Загружает переданные файлы в указанную директорию
* 
*/
class Learning_Backend_Common_File_Upload 
{
    
    /**
    * @param array [$FILES] 
    * @param string [$dest_folder]
    * 
    * @desc upload file to the specified directory 
    * 
    * @return array [file name(s)]
    */
    static public function upload($FILES, $dest_folder) 
    {
        $dst_names = array();
        foreach ($FILES['tmp_name'] as $index => $tmp_name) {
            if (0 == $FILES['error'][$index] && 
                '' != trim($FILES['name'][$index])) 
            {
                $dst_names[] = $dst_name = self::getOutputName(
                    $FILES['name'][$index], 
                    $dest_folder
                );
                copy($tmp_name, $dest_folder . $dst_name);
            }
        }
        return $dst_names;
    }
    
    /**
    * @param string file name, string destination folder
    * 
    * @desc chechk wether a file with such name already exists
    * and in such case add '_rand' to output file name
    * 
    * @return string output name
    */
    static protected function getOutputName($name, $dest_folder) 
    {
        $handle_dir = opendir($dest_folder);
        while (($file = readdir($handle_dir)) !== false) {
            if (strtolower($file) == strtolower($name)) {
                preg_match('/(.*)(\.[a-zA-z0-9]+)/', $name, $pockets);
                $name = $pockets[1] . '_' . rand(0, 100000) . $pockets[2];
                break;
            }
        }
        return $name;
    }
    
}
